<?php
namespace app\index\controller;
use app\index\model\Wechat;

class File extends Base
{
    public function upload()
    {
        $file = $this->request->file('picture');
        $info = $file->validate(['size' => 512000,'ext' => 'jpg,png,jpeg']) //, 'type' => 'image/jpeg,image/png'
            ->move(ROOT_PATH . 'public' . DS . 'uploads');

        if($info) {
            return $this->jsonSuccess('上传成功', ['path' => '/uploads/' . date('Ymd') . '/' . $info->getFilename()]);
        } else {
            return $this->jsonError($file->getError());
        }
    }

    public function uploadVoice()
    {
        $media_id = $this->request->param('media_id');
        $wechatConfig = config('wechat');
        $options = array(
            'token' => $wechatConfig['wechat_token'],             //填写你设定的key
            'encodingaeskey' => $wechatConfig['wechat_encodingaeskey'],   //填写加密用的EncodingAESKey，如接口为明文模式可忽略
            'appid' => $wechatConfig['wechat_appid'],            //填写高级调用功能的app id
            'appsecret' => $wechatConfig['wechat_appsecret']            //填写高级调用功能的密钥
        );
        $wechat = new Wechat($options);
        $result = $wechat->getMedia($media_id);

        if($result) {
            $path = ROOT_PATH . 'public' . DS . 'uploads'. DS . 'media' . DS;
            $fileName = time().rand(1111,9999);
            if(!is_dir($path)) mkdir($path);
            // 讲获取到的文件保存
            $fp = fopen($path . $fileName . '.amr', 'a');
            fwrite($fp, $result);
            fclose($fp);
            // 生成转码后的文件
            $command = '/usr/local/bin/ffmpeg -i ' . $path . $fileName . '.amr ' . $path . $fileName . '.mp3';
            exec($command);
            // 删除转码前的文件
            unlink($path . $fileName . '.amr');
            return $this->jsonSuccess('录音成功', ['path' => '/uploads/media/' . $fileName . '.mp3']);
        } else {
            return $this->jsonFail('录音失败');
        }

    }
}
